package com.zhangcl.Threadtest;

/**
 * 子线程循环10次，接着主线程循环20次，接着又回到子线程循环10次，接着再回到主线程又循环20次,如此循环50次,请写出程序。
 * @author ZhangChunLiang
 *
 */
public class TraditionarySynTest2 {
	final Busniess busniess = new Busniess();
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new TraditionarySynTest2().executeFun();
	}
	public void executeFun(){
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				for (int i = 1; i <= 50; i++) {
					busniess.sub(i);
				}
				
			}
		}).start();
		for (int i = 1; i <= 50; i++) {
			busniess.main(i);
		}
	};
	
	
	class Busniess {
		boolean isSubExecucte;
		public void main(int j){
			synchronized (this) {
				while (isSubExecucte) {
					try {
						this.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				for (int i = 1; i <= 20; i++) {
					System.out.println("Main sequnce is "+i+",loop of"+j);
				}
				isSubExecucte = true;
				this.notify();
			}
		}
		
		public void sub(int j){
			synchronized (this) {
				while (!isSubExecucte) {
					try {
						this.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				for (int i = 1; i <= 10 ; i++) {
					System.out.println("Sub sequnce is "+i+ ",loop of"+j);
				}
				isSubExecucte = false;
				this.notify();
			}
		}
	}
}
